package com.feeling.oafeeling.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.feeling.oafeeling.common.BaseContext;
import com.feeling.oafeeling.pojo.SysUser;
import com.feeling.oafeeling.service.ISysUserService;
import com.feeling.oafeeling.utils.util.IpUtil;
import com.feeling.oafeeling.utils.util.RedisPreEnum;
import com.feeling.oafeeling.utils.util.RedisUtil;
import com.feeling.oafeeling.utils.util.anno.PassToken;
import com.feeling.oafeeling.utils.util.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


public class AuthenticationInterceptor implements HandlerInterceptor {
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    ISysUserService userService;
    @Autowired
    TokenService tokenService;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        String token=httpServletRequest.getHeader("Access-Token");
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            boolean required = passToken.required();
            if (required) {
                return true;
            }
        }
        if (token == null) {
            throw new RuntimeException("无token，请重新登录");
        }
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new Exception("token无效");
        }
        SysUser user = null;
        String key = RedisPreEnum.JWT_TOKEN_PRE.getPre() + userId + IpUtil.getRemoteAddr(httpServletRequest);;
        if (redisUtil.hasKey(key)) {
            Object o = redisUtil.get(userId);
            user = JSONObject.toJavaObject((JSON) JSON.toJSON(o), SysUser.class);
        }
        if (user == null) {
            throw new RuntimeException("请重新登录");
        }
        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TokenService.TOKEN_SECRET)).build();
        try {
            jwtVerifier.verify(token);
        } catch (Exception e) {
            throw new Exception("token无效");
        }
        BaseContext.setCurrentId(tokenService.verifyTokenForName(token));
        return true;


//
//        Object o1 = redisUtil.get(key);
//
//        // 如果不是映射到方法直接通过
//        if (!(object instanceof HandlerMethod)) {
//            return true;
//        }
//        HandlerMethod handlerMethod = (HandlerMethod) object;
//        Method method = handlerMethod.getMethod();
//        //检查是否有passtoken注释，有则跳过认证
//        if (method.isAnnotationPresent(PassToken.class)) {
//            PassToken passToken = method.getAnnotation(PassToken.class);
//            if (passToken.required()) {
//                return true;
//            }
//        }
//        if (token == null) {
////            return true;
//            throw new RuntimeException("无token，请重新登录");
//        }else {
//
//        }
//        String userId;
//        try {
//            userId = JWT.decode(token).getAudience().get(0);
//        } catch (JWTDecodeException j) {
//            throw new Exception("token无效");
//        }
//        User user = null;
//        String key = RedisPreEnum.JWT_TOKEN_PRE.getPre() + userId + IpUtil.getIpAddr(httpServletRequest);
//        if (redisUtil.hasKey(key)) {
//            Object o = redisUtil.get(key);
//            user = JSONObject.toJavaObject((JSON) JSON.toJSON(o), User.class);
//        }
//        if (user == null) {
//            throw new RuntimeException("请重新登录");
//        }
//        // 验证 token
//        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
//        try {
//            jwtVerifier.verify(token);
//        } catch (Exception e) {
//            throw new Exception("token无效");
//        }
//        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
